<script setup lang="ts">
    import * as d3 from 'd3';
    import { reactive,onMounted,useTemplateRef } from 'vue';

    const chartBox = useTemplateRef('chart');


    onMounted(async ()=>{
        const chatDom = await drawChart();
        console.log(chatDom);
       chartBox.value.append(chatDom);
    })

    const drawChart = async () => {

        const aapl = await d3.csv("../dataBase/aapl.csv");

        const width = 928;
        const height = 500;
        const marginTop = 20;
        const marginRight = 30;
        const marginBottom = 30;
        const marginLeft = 40;

        // Declare the x (horizontal position) scale.
        const x = d3.scaleTime(d3.extent(aapl, d => new Date(d.date)), [marginLeft, width - marginRight]);
        // Declare the y (vertical position) scale.
        console.log(x.ticks(1));

        const y = d3.scaleLinear([0, d3.max(aapl, d => d.close)], [height - marginBottom, marginTop]);

        // Declare the area generator.
        // const area = d3.area()
        // .x0(d => x(d.date))
        // .y0(y(0))
        // .y1(d => y(d.close));

        const area = d3.area((d) => x(new Date(d.date)), y(0), (d) => y(d.close));

        const line = d3.line()
        .x(d => x(new Date(d.date)))
        .y(d => y(d.close));

        // Create the SVG container.
        const svg = d3.create("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("viewBox", [0, 0, width, height])
        .attr("style", "max-width: 100%; height: auto;");

        // Append a path for the area (under the axes).
        // console.log(area(aapl));
        svg.append("path")
        .attr("fill", "steelblue")
        .attr("d", line(aapl));

        // Add the x-axis.
        svg.append("g")
        .attr("transform", `translate(0,${height - marginBottom})`)
        .call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0));

        // Add the y-axis, remove the domain line, add grid lines and a label.
        svg.append("g")
        .attr("transform", `translate(${marginLeft},0)`)
        .call(d3.axisLeft(y).ticks(height / 40))
        .call(g => g.select(".domain").remove())
        .call(g => g.selectAll(".tick line").clone()
            .attr("x2", width - marginLeft - marginRight)
            .attr("stroke-opacity", 0.1))
        .call(g => g.append("text")
            .attr("x", -marginLeft)
            .attr("y", 10)
            .attr("fill", "currentColor")
            .attr("text-anchor", "start")
            .text("↑ Daily close ($)"));

        return svg.node();
    }
</script>
<template>
  <div ref="chart" class="graph"></div>
</template>
<style scoped>
.graph {
  background-color: #d1e9ff;
}
</style>